<template>
  <div class="page_root">
    <div class="header">
      <div class="form_wrapper">
        <div class="title_wrapper">
          <var-input v-model.trim="form.title" placeholder="请输入文章标题" />
        </div>
        <div class="btn_row">
          <var-button primary @click="insertImg"> 插入图片 </var-button>
          <input
            ref="upload-input"
            type="file"
            hidden
            @change="handlerUploadFileChange"
          />
          <var-button primary class="submit_btn" @click="preSubmit">
            发布
          </var-button>
        </div>
        <img
          src="./images/close.svg"
          class="back_btn"
          alt=""
          @click="$router.back()"
        />
      </div>
    </div>

    <div class="editor_section">
      <div class="editor_wrapper">
        <Editor :default-value="form.content" @onInput="editorChange" />
      </div>
      <div class="preview_wrapper">
        <Preview :content="html" />
      </div>
    </div>
  </div>
</template>
<script>
import * as http from "./api";
import Editor from "./editor";
import Preview from "./preview";
import { throttle } from "@/utils";
export default {
  components: {
    Editor,
    Preview,
  },
  data() {
    return {
      dialogVisiable: false,
      labelFilterKeywords: "",
      labelDict: [],
      folderDict: [],
      form: {
        id: "",
        title: "",
        content: "",
        hash: "",
        html: "",
      },
    };
  },
  computed: {
    html() {
      return this.form.content
        .replace(
          /\.\/images\/((.*?)\.(png|jpg|gif|jpeg))/g,
          `${process.env.API_ORIGIN}/static/blogs/${this.form.hash}/images/$1`
        )
        .replace(/\t/g, "    ");
    },
  },

  async mounted() {
    // 如果有hash，就是编辑文章，先获取文章详情
    const hash = this.$route.params.hash || "";
    if (hash) {
      try {
        const res = await http.selectBlogOne({
          id: hash,
        });
        if (res.code !== 200) {
          this.$message.error(res.msg);
          return;
        }
        this.form.id = res.data.blog.id;
        this.form.title = res.data.blog.name;
        this.form.content = res.data.blog.content.replace(/\t/g, "    ");
        this.form.hash = res.data.blog.hash;
        this.form.status = res.data.blog.status;
      } catch (e) {
        console.log(e);
      }
    }
  },
  methods: {
    editorChange: throttle(function (data) {
      if (data.instance === this.form.content) {
        return;
      }
      this.form.content = data.instance;
      if (this.form.id) {
        // 有id表示是编辑文章，可以自动保存了
        this.submitBlog(true);
      }
    }, 2000),
    async insertImg() {
      // 插入图片
      // this.selectedFile = '';
      this.$refs["upload-input"].value = "";
      this.$refs["upload-input"].click();
    },
    async handlerUploadFileChange(e) {
      // 上传文件发生变化
      const formData = new FormData();
      formData.append("files", e.target.files[0]);
      formData.append("type", "blog");
      formData.append("id", this.form.id);
      try {
        const res = await http.uploadFile(formData);
        console.log("handlerUploadFileChange", res);
        this.form.id = res.data.blog.id;
        this.form.hash = res.data.blog.hash;
        this.form.content += `\n![](${res.data.path})`;
      } catch (e) {
        console.log(e);
      }
    },
    async preSubmit() {
      if (this.form.title === "") {
        this.$message.error("标题不能为空");
        return;
      }
      if (this.form.content === "") {
        this.$message.error("内容不能为空");
        return;
      }
      this.submitBlog();
    },
    async submitBlog(autosave = false) {
      // 发布文章
      if (this.form.id === "") {
        // 如果没有ID就是新增
        try {
          const res = await http.insertBlog(this.form);

          this.form.id = res.data.id + "";
        } catch (e) {
          console.log(e);
          this.$message.error(e.msg || "网路错误");
          return;
        }
      } else {
        // 如果有ID就是更新内容
        try {
          await http.updateBlog(this.form);
          // this.form.content = res.data.content;
        } catch (e) {
          console.log(e);
          this.$message.error(e.msg || "网路错误");
          return;
        }
      }
      this.$message.success(autosave ? "自动保存成功" : "发布成功");
    },
  },
};
</script>
<style lang="scss" scoped>
.page_root {
  padding: 0 10px;
  height: calc(100vh - 10px);
  min-height: 500px;
  display: flex;
  flex-direction: column;
  background: url("./images/page_bg.png");
  .header {
    position: sticky;
    z-index: 10;
    top: 0;
    background: url("./images/page_bg.png");
    padding: 10px 0;
    .form_wrapper {
      display: flex;
      .title_wrapper {
        flex-grow: 1;
        flex-shrink: 0;
        margin-right: 10px;
      }
      .btn_row {
        display: flex;
        align-items: center;
        .submit_btn {
          margin-left: 10px;
        }
      }
      .back_btn {
        display: block;
        width: 30px;
        height: 30px;
        margin-left: 300px;
        cursor: pointer;
      }
    }
  }
  .form_item {
    display: flex;
    align-items: center;
    .label {
      width: 50px;
      padding-right: 10px;
      text-align: center;
    }
  }
  .tag_row {
    margin: 10px 0;
    .tag_list {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      .tag_item {
        margin-right: 10px;
        cursor: pointer;
        padding: 0 6px;
        background-color: rgb(89, 89, 89);
        color: white;
        height: 20px;
        line-height: 20px;
        &.success {
          background-color: red;
        }
      }
    }
  }
  .editor_section {
    flex-grow: 1;
    display: flex;
    overflow: hidden;
    > div {
      width: 50%;
      height: 100%;
      flex-grow: 1;
    }
    .editor_wrapper {
      border-right: 1px solid $border-color;
      border-left: 1px solid $border-color;
      border-top: 1px solid $border-color;
      .vue-codemirror {
        height: 100%;
      }

      .textarea {
        display: block;
        width: 100%;
        height: 100%;
        border: none;
        resize: none;
        &:focus {
          border: none;
          outline: none;
        }
      }
    }
    .preview_wrapper {
      border-right: 1px solid $border-color;
      border-top: 1px solid $border-color;
      padding: 0 10px;
      font-size: 16px;
      line-height: 1.4em;
      height: 100%;
      overflow-y: auto;
      background-color: white;
      ::v-deep {
        p {
          code {
            color: #0099ff;
          }
        }
        // pre {
        // margin: 0;
        // }
      }
    }
  }
}
</style>
